# Untitled - By: lenovo - Fri Jul 26 2024


import sensor
import image
import random
import machine
from pyb import UART
from pyb import LED
from image import SEARCH_EX, SEARCH_DS

sensor.reset()
sensor.set_pixformat(sensor.GRAYSCALE)
sensor.set_framesize(sensor.QQVGA)
sensor.skip_frames(time=2000)


# 创建串口通信对象
uart = UART(3, 115200, bits=8, parity=None, stop=1)
# 创建image对象
img = sensor.snapshot()
# led灯光
led = LED(random.randint(1, 3))

def LED_Show():
    global led
    led.off()
    led = LED(random.randint(1, 3))
    led.on()

def LED_Off():
    global led
    led.off()


def DrawRecognizeXY(corners):
    global img
    img.draw_circle(corners[0][0], corners[0][1], 5, color=(255, 0, 0))
    img.draw_circle(corners[1][0], corners[1][1], 5, color=(0, 255, 0))
    img.draw_circle(corners[2][0], corners[2][1], 5, color=(0, 0, 255))
    img.draw_circle(corners[3][0], corners[3][1], 5, color=(255, 255, 255))


# 发送坐标数据
def UART_SendRecognizeXY(recognize):
    global uart
    # 从左上角开始顺时针返回坐标
    corners = [[recognize[0], recognize[1]], [recognize[0] + recognize[2], recognize[1]], [recognize[0] + recognize[2], recognize[1] + recognize[3]], [recognize[0], recognize[1] + recognize[3]]]
    for XY in corners:
        sendarray = str(XY[0]) + ' ' + str(XY[1])
        uart.write(sendarray)
        print(sendarray)
    print('')
    DrawRecognizeXY(corners)


template = image.Image("/template/three.pgm")

while True:
    img = sensor.snapshot()

    target = img.find_template(template, 0.70, step=4, search=SEARCH_EX)

    if target:
        LED_Show()
        img.draw_rectangle(target)
        UART_SendRecognizeXY(target)
    else:
        LED_Off()
